<template>
  <div class="search-box-container" ref="containerRef">
    <!-- 搜索输入框 -->
    <div class="search-input-wrapper" :class="{ 'is-focused': isFocused, 'has-results': showDropdown }">
      <div class="search-icon">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="11" cy="11" r="8"/>
          <path d="m21 21-4.35-4.35"/>
        </svg>
      </div>
      
      <!-- 输入框容器（支持自动补全显示） -->
      <div class="input-container">
        <input
          ref="inputRef"
          type="text"
          class="search-input"
          v-model="searchQuery"
          :placeholder="placeholder"
          @input="handleInput"
          @focus="handleFocus"
          @blur="handleBlur"
          @keydown="handleKeydown"
          @compositionstart="isComposing = true"
          @compositionend="handleCompositionEnd"
          autocomplete="off"
        />
        <!-- 自动补全提示（灰色文字） -->
        <div 
          v-if="suggestion && !isComposing" 
          class="autocomplete-hint"
          @click="acceptSuggestion"
        >
          <span class="hint-prefix">{{ searchQuery }}</span>
          <span class="hint-suffix">{{ suggestionSuffix }}</span>
          <span class="hint-tab">Tab</span>
        </div>
      </div>
      
      <div class="search-actions">
        <button 
          v-if="searchQuery" 
          class="clear-btn" 
          @mousedown.prevent="clearSearch"
          title="清除"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 6 6 18M6 6l12 12"/>
          </svg>
        </button>
        <button 
          class="search-btn" 
          @mousedown.prevent="handleSearchClick"
          :disabled="!searchQuery.trim()"
        >
          搜索
        </button>
      </div>
    </div>
    
    <!-- 下拉结果列表 -->
    <Transition name="dropdown">
      <div 
        v-if="showDropdown" 
        class="search-dropdown"
        ref="dropdownRef"
      >
        <!-- 加载状态 -->
        <div v-if="isLoading" class="dropdown-loading">
          <div class="loading-spinner"></div>
          <span>搜索中...</span>
        </div>
        
        <!-- 无结果 -->
        <div v-else-if="results.length === 0 && searchQuery.trim() && !isLoading" class="dropdown-empty">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
            <circle cx="12" cy="12" r="10"/>
            <path d="m15 9-6 6M9 9l6 6"/>
          </svg>
          <span>未找到相关测站</span>
        </div>
        
        <!-- 结果列表 -->
        <ul v-else class="dropdown-list">
          <li
            v-for="(item, index) in results"
            :key="item.code"
            class="dropdown-item"
            :class="{ 'is-active': activeIndex === index }"
            @mouseenter="activeIndex = index"
            @mousedown.prevent="selectItem(item)"
          >
            <div class="item-icon">
              <span class="station-type-badge" :data-type="item.type">
                {{ getTypeIcon(item.type) }}
              </span>
            </div>
            <div class="item-content">
              <div class="item-name">
                {{ item.name }}
                <span class="item-code">{{ item.code }}</span>
              </div>
              <div class="item-meta">
                <span class="meta-tag type">{{ getStationTypeName(item.type) }}</span>
                <span v-if="item.match_type" class="meta-tag match">
                  {{ getMatchTypeName(item.match_type) }}
                </span>
                <span class="meta-score">匹配度 {{ Math.round(item.score * 100) }}%</span>
              </div>
            </div>
            <div class="item-arrow">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="m9 18 6-6-6-6"/>
              </svg>
            </div>
          </li>
        </ul>
        
        <!-- 底部提示 -->
        <div v-if="results.length > 0" class="dropdown-footer">
          <span class="hint">
            <kbd>↑</kbd><kbd>↓</kbd> 导航
            <kbd>Tab</kbd> 补全
            <kbd>Enter</kbd> 选择
          </span>
          <span class="result-count">共 {{ results.length }} 个结果</span>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { searchStations, suggestStation, getStationTypeName } from './api.js'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索测站名称、编码、别名...'
  },
  debounceTime: {
    type: Number,
    default: 300
  }
})

const emit = defineEmits(['select', 'search'])

// Refs
const containerRef = ref(null)
const inputRef = ref(null)
const dropdownRef = ref(null)

// State
const searchQuery = ref('')
const results = ref([])
const isLoading = ref(false)
const isFocused = ref(false)
const activeIndex = ref(-1)
const isComposing = ref(false) // 中文输入法状态

// 自动补全
const suggestion = ref(null) // { name, type, code }
let debounceTimer = null
let suggestTimer = null

// 计算补全后缀
const suggestionSuffix = computed(() => {
  if (!suggestion.value || !searchQuery.value) return ''
  const query = searchQuery.value
  const name = suggestion.value.name
  // 如果建议的名称以当前输入开头，返回补全部分
  if (name.toLowerCase().startsWith(query.toLowerCase())) {
    return name.slice(query.length)
  }
  return ''
})

// 是否显示下拉
const showDropdown = computed(() => {
  return isFocused.value && (isLoading.value || results.value.length > 0 || (searchQuery.value.trim() && !isLoading.value))
})

// 站点类型图标映射
const typeIconMap = {
  'RESERVOIR': '🏭',
  'RR': '🏭',
  'PP': '🌧️',
  'ZZ': '📊',
  'ZQ': '📈',
  'DD': '🚧',
  'MM': '🌡️',
  'DEFAULT': '📍'
}

function getTypeIcon(type) {
  return typeIconMap[type] || typeIconMap['DEFAULT']
}

// 匹配类型中文映射
function getMatchTypeName(matchType) {
  const map = {
    'exact': '精确匹配',
    'prefix': '前缀匹配',
    'contains': '包含匹配',
    'contains_alias': '别名匹配',
    'alias': '别名匹配',
    'fuzzy': '模糊匹配',
    'name': '名称匹配',
    'code': '编码匹配'
  }
  return map[matchType] || matchType
}

// 处理输入
function handleInput() {
  // 如果正在中文输入，不触发搜索
  if (isComposing.value) return
  
  doSearch()
}

// 处理中文输入结束
function handleCompositionEnd(e) {
  isComposing.value = false
  searchQuery.value = e.target.value
  doSearch()
}

// 执行搜索逻辑
function doSearch() {
  activeIndex.value = -1
  
  // 清除之前的定时器
  if (debounceTimer) clearTimeout(debounceTimer)
  if (suggestTimer) clearTimeout(suggestTimer)
  
  const query = searchQuery.value.trim()
  
  if (!query) {
    results.value = []
    suggestion.value = null
    isLoading.value = false
    return
  }
  
  // 快速触发自动补全建议（100ms）
  suggestTimer = setTimeout(async () => {
    try {
      const result = await suggestStation(query)
      if (result && searchQuery.value.trim() === query) {
        suggestion.value = result
      } else {
        suggestion.value = null
      }
    } catch (error) {
      suggestion.value = null
    }
  }, 100)
  
  // 搜索列表（300ms）
  isLoading.value = true
  debounceTimer = setTimeout(async () => {
    try {
      const data = await searchStations(query)
      if (searchQuery.value.trim() === query) {
        results.value = data.matches || []
      }
    } catch (error) {
      console.error('搜索失败:', error)
      results.value = []
    } finally {
      isLoading.value = false
    }
  }, props.debounceTime)
}

// 接受自动补全建议
function acceptSuggestion() {
  if (suggestion.value) {
    searchQuery.value = suggestion.value.name
    suggestion.value = null
    // 直接选择这个测站
    selectItem({
      name: suggestion.value?.name || searchQuery.value,
      code: suggestion.value?.code,
      type: suggestion.value?.type
    })
  }
}

// 焦点处理
function handleFocus() {
  isFocused.value = true
}

function handleBlur() {
  setTimeout(() => {
    isFocused.value = false
    activeIndex.value = -1
  }, 150)
}

// 键盘导航
function handleKeydown(e) {
  // Tab 键接受自动补全
  if (e.key === 'Tab' && suggestion.value && suggestionSuffix.value) {
    e.preventDefault()
    searchQuery.value = suggestion.value.name
    suggestion.value = null
    doSearch()
    return
  }
  
  // 右箭头在光标在末尾时也接受补全
  if (e.key === 'ArrowRight' && suggestion.value && suggestionSuffix.value) {
    const input = inputRef.value
    if (input && input.selectionStart === searchQuery.value.length) {
      e.preventDefault()
      searchQuery.value = suggestion.value.name
      suggestion.value = null
      doSearch()
      return
    }
  }
  
  if (!showDropdown.value || results.value.length === 0) {
    if (e.key === 'Enter' && searchQuery.value.trim()) {
      // 如果有建议，直接选择建议的测站
      if (suggestion.value) {
        e.preventDefault()
        selectItem({
          name: suggestion.value.name,
          code: suggestion.value.code,
          type: suggestion.value.type
        })
        return
      }
      emit('search', searchQuery.value.trim())
    }
    return
  }
  
  switch (e.key) {
    case 'ArrowDown':
      e.preventDefault()
      activeIndex.value = (activeIndex.value + 1) % results.value.length
      scrollToActive()
      break
    case 'ArrowUp':
      e.preventDefault()
      activeIndex.value = activeIndex.value <= 0 
        ? results.value.length - 1 
        : activeIndex.value - 1
      scrollToActive()
      break
    case 'Enter':
      e.preventDefault()
      if (activeIndex.value >= 0 && activeIndex.value < results.value.length) {
        selectItem(results.value[activeIndex.value])
      } else if (suggestion.value) {
        // 没有选中列表项但有建议，使用建议
        selectItem({
          name: suggestion.value.name,
          code: suggestion.value.code,
          type: suggestion.value.type
        })
      } else if (results.value.length > 0) {
        selectItem(results.value[0])
      } else if (searchQuery.value.trim()) {
        emit('search', searchQuery.value.trim())
      }
      break
    case 'Escape':
      e.preventDefault()
      isFocused.value = false
      inputRef.value?.blur()
      break
  }
}

// 滚动到激活项
function scrollToActive() {
  nextTick(() => {
    const dropdown = dropdownRef.value
    const activeItem = dropdown?.querySelector('.dropdown-item.is-active')
    if (activeItem && dropdown) {
      activeItem.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
    }
  })
}

// 选择项目
function selectItem(item) {
  searchQuery.value = item.name
  isFocused.value = false
  results.value = []
  suggestion.value = null
  emit('select', item)
}

// 清除搜索
function clearSearch() {
  searchQuery.value = ''
  results.value = []
  suggestion.value = null
  activeIndex.value = -1
  inputRef.value?.focus()
}

// 搜索按钮点击
function handleSearchClick() {
  if (searchQuery.value.trim()) {
    if (activeIndex.value >= 0 && results.value[activeIndex.value]) {
      selectItem(results.value[activeIndex.value])
    } else if (suggestion.value) {
      selectItem({
        name: suggestion.value.name,
        code: suggestion.value.code,
        type: suggestion.value.type
      })
    } else if (results.value.length > 0) {
      selectItem(results.value[0])
    } else {
      emit('search', searchQuery.value.trim())
    }
  }
}

// 点击外部关闭
function handleClickOutside(e) {
  if (containerRef.value && !containerRef.value.contains(e.target)) {
    isFocused.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
  if (debounceTimer) clearTimeout(debounceTimer)
  if (suggestTimer) clearTimeout(suggestTimer)
})

// 暴露方法
defineExpose({
  focus: () => inputRef.value?.focus(),
  clear: clearSearch
})
</script>

<style scoped>
.search-box-container {
  position: relative;
  width: 100%;
}

/* 搜索输入框外层 */
.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 18px;
  background: rgba(30, 41, 59, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(20px);
}

.search-input-wrapper:hover {
  border-color: rgba(255, 255, 255, 0.25);
  background: rgba(30, 41, 59, 0.95);
}

.search-input-wrapper.is-focused {
  border-color: #00d4ff;
  box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.2), 0 8px 32px rgba(0, 0, 0, 0.3);
  background: rgba(30, 41, 59, 0.98);
}

.search-input-wrapper.has-results {
  border-radius: 16px 16px 0 0;
  border-bottom-color: transparent;
}

/* 搜索图标 */
.search-icon {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  color: #64748b;
  transition: color 0.2s;
}

.search-input-wrapper.is-focused .search-icon {
  color: #00d4ff;
}

.search-icon svg {
  width: 100%;
  height: 100%;
}

/* 输入框容器 */
.input-container {
  flex: 1;
  min-width: 0;
  position: relative;
}

/* 输入框 */
.search-input {
  width: 100%;
  border: none;
  outline: none;
  background: transparent;
  font-size: 15px;
  font-weight: 400;
  color: #f1f5f9;
  font-family: 'PingFang SC', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif;
}

.search-input::placeholder {
  color: #64748b;
  font-weight: 400;
}

/* 自动补全提示 */
.autocomplete-hint {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 100%;
  display: flex;
  align-items: center;
  pointer-events: none;
  font-size: 15px;
  font-family: 'PingFang SC', 'Microsoft YaHei', -apple-system, BlinkMacSystemFont, sans-serif;
}

.hint-prefix {
  color: transparent;
}

.hint-suffix {
  color: #475569;
}

.hint-tab {
  margin-left: 8px;
  padding: 2px 6px;
  background: rgba(0, 212, 255, 0.15);
  border-radius: 4px;
  font-size: 10px;
  color: #00d4ff;
  font-weight: 500;
  pointer-events: auto;
  cursor: pointer;
}

.hint-tab:hover {
  background: rgba(0, 212, 255, 0.25);
}

/* 操作按钮区 */
.search-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.clear-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  border: none;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  cursor: pointer;
  color: #94a3b8;
  transition: all 0.2s;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  color: #f1f5f9;
}

.clear-btn svg {
  width: 14px;
  height: 14px;
}

.search-btn {
  padding: 8px 18px;
  border: none;
  background: linear-gradient(135deg, #00d4ff 0%, #0066ff 100%);
  color: white;
  font-size: 14px;
  font-weight: 500;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #00e5ff 0%, #0077ff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 16px rgba(0, 212, 255, 0.4);
}

.search-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

/* 下拉框 */
.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(30, 41, 59, 0.98);
  border: 1px solid #00d4ff;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0 0 16px 16px;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.4);
  overflow: hidden;
  z-index: 1000;
  backdrop-filter: blur(20px);
}

/* 下拉动画 */
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.2s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 加载状态 */
.dropdown-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 32px;
  color: #94a3b8;
}

.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-top-color: #00d4ff;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 空状态 */
.dropdown-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 40px;
  color: #64748b;
}

.dropdown-empty svg {
  width: 48px;
  height: 48px;
  opacity: 0.5;
}

/* 结果列表 */
.dropdown-list {
  list-style: none;
  margin: 0;
  padding: 8px 0;
  max-height: 400px;
  overflow-y: auto;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 14px 18px;
  cursor: pointer;
  transition: all 0.15s;
}

.dropdown-item:hover,
.dropdown-item.is-active {
  background: rgba(0, 212, 255, 0.1);
}

.dropdown-item.is-active {
  background: rgba(0, 212, 255, 0.15);
}

/* 项目图标 */
.item-icon {
  flex-shrink: 0;
}

.station-type-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  font-size: 20px;
  background: linear-gradient(135deg, rgba(0, 212, 255, 0.2) 0%, rgba(0, 102, 255, 0.2) 100%);
  border-radius: 12px;
  border: 1px solid rgba(0, 212, 255, 0.2);
}

/* 项目内容 */
.item-content {
  flex: 1;
  min-width: 0;
}

.item-name {
  font-size: 15px;
  font-weight: 500;
  color: #f1f5f9;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-code {
  font-size: 12px;
  font-weight: 400;
  color: #64748b;
  font-family: 'Monaco', 'Consolas', monospace;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.meta-tag {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  font-size: 11px;
  font-weight: 500;
  border-radius: 4px;
}

.meta-tag.type {
  background: rgba(59, 130, 246, 0.2);
  color: #60a5fa;
}

.meta-tag.match {
  background: rgba(34, 197, 94, 0.2);
  color: #4ade80;
}

.meta-score {
  font-size: 11px;
  color: #64748b;
}

/* 箭头 */
.item-arrow {
  flex-shrink: 0;
  width: 18px;
  height: 18px;
  color: #475569;
  transition: all 0.2s;
}

.dropdown-item:hover .item-arrow,
.dropdown-item.is-active .item-arrow {
  color: #00d4ff;
  transform: translateX(4px);
}

.item-arrow svg {
  width: 100%;
  height: 100%;
}

/* 底部提示 */
.dropdown-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 18px;
  background: rgba(15, 23, 42, 0.8);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  font-size: 11px;
  color: #64748b;
}

.hint {
  display: flex;
  align-items: center;
  gap: 6px;
}

.hint kbd {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
  height: 18px;
  padding: 0 5px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 4px;
  font-family: inherit;
  font-size: 10px;
  color: #94a3b8;
}

.result-count {
  color: #64748b;
}

/* 滚动条样式 */
.dropdown-list::-webkit-scrollbar {
  width: 6px;
}

.dropdown-list::-webkit-scrollbar-track {
  background: transparent;
}

.dropdown-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.dropdown-list::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}
</style>
